import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getToolList } from '../../services/tools';

const Tools: React.FC = () => {
  const [tools, setTools] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  
  const navigate = useNavigate();
  
  useEffect(() => {
    fetchToolList();
  }, []);
  
  const fetchToolList = async () => {
    try {
      setLoading(true);
      setError('');
      
      const response = await getToolList();
      
      if (response.code === 200) {
        setTools(response.data.tools || []);
      } else {
        setError(response.message || '获取工具列表失败');
      }
    } catch (err: any) {
      setError(err.message || '获取工具列表失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  // 预设工具列表（如果API未返回数据）
  const defaultTools = [
    {
      id: 'calendar',
      name: '万年历',
      icon: '📅',
      description: '查询公历、农历日期，节气、节日等信息',
      path: '/tools/calendar'
    },
    {
      id: 'zodiac',
      name: '星座与生肖',
      icon: '🌟',
      description: '查询星座与生肖特点、运势等信息',
      path: '/tools/zodiac'
    },
    {
      id: 'name',
      name: '姓名测算',
      icon: '📝',
      description: '分析姓名的五行属性、吉凶、运势等',
      path: '/tools/name'
    },
    {
      id: 'dream',
      name: '周公解梦',
      icon: '💤',
      description: '解析梦境寓意与预示',
      path: '/tools/dream'
    }
  ];
  
  const displayTools = tools.length > 0 ? tools : defaultTools;
  
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-4xl mx-auto">
        <div className="text-center mb-12">
          <h2 className="text-3xl font-bold text-gray-900">实用小工具</h2>
          <p className="mt-2 text-lg text-gray-600">
            提供多种实用工具，助您了解更多命理知识
          </p>
        </div>
        
        {error && (
          <div className="text-red-500 text-center mb-6">
            {error}
          </div>
        )}
        
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-2">
          {displayTools.map((tool) => (
            <div
              key={tool.id}
              className="bg-white overflow-hidden shadow rounded-lg hover:shadow-md transition-shadow duration-300 cursor-pointer"
              onClick={() => navigate(tool.path)}
            >
              <div className="p-6">
                <div className="flex items-center">
                  <div className="flex-shrink-0 bg-indigo-100 rounded-md p-3 text-2xl">
                    {tool.icon}
                  </div>
                  <div className="ml-4">
                    <h3 className="text-lg font-medium text-gray-900">{tool.name}</h3>
                    <p className="mt-1 text-sm text-gray-500">
                      {tool.description}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
        
        <div className="mt-12 text-center">
          <p className="text-sm text-gray-500">
            注：未登录用户部分工具每次使用需支付1.1元，登录用户0.1元/次，VIP会员无限使用
          </p>
        </div>
      </div>
    </div>
  );
};

export default Tools;
